package com.xyt.imei.core.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.luminary.common.framework.core.auth.ValidateToken;
import com.luminary.common.framework.core.model.Pagination;
import com.luminary.common.framework.core.model.SimpleResponse;
import com.luminary.component.util.common.BeanMapUtils;
import com.luminary.component.util.common.DateUtil;
import com.luminary.component.util.common.ExcelUtil;
import com.xyt.imei.core.meta.PageConstants;
import com.xyt.imei.core.meta.RoleEnum;
import com.xyt.imei.core.model.dto.TaskDetailDTO;
import com.xyt.imei.core.model.dto.TaskDetailExcelDTO;
import com.xyt.imei.core.model.dto.TaskQueryDTO;
import com.xyt.imei.core.model.po.Task;
import com.xyt.imei.core.model.po.TaskDetail;
import com.xyt.imei.core.model.po.User;
import com.xyt.imei.core.service.TaskService;
import com.xyt.imei.core.util.TokenUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("task")
public class TaskApi {

	@Autowired
	private TokenUtil tokenUtil;
	
	@Autowired
	private TaskService taskService;
	
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "",  RoleEnum.CMCC_VALUE + "", RoleEnum.BRANCH_VALUE + ""})
	@GetMapping("/page")
	public SimpleResponse query(
			@Valid TaskQueryDTO taskQueryDTO,
			@PageableDefault(page=PageConstants.DEFAULT_PAGE_NO,size=PageConstants.DEFAULT_PAGE_SIZE)
			@SortDefault.SortDefaults({
				@SortDefault(sort = "create_date", direction = Direction.DESC)
			}) Pageable pageable,
			HttpServletResponse response) throws Exception {
		log.info("taskQueryDTO:" + taskQueryDTO.toString() + ",pageable:" + pageable.toString());
		
		User user = tokenUtil.getUser();
		
		Pagination<Task> pagination = new Pagination<Task>(pageable);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params = BeanMapUtils.beanToMap(taskQueryDTO);
		params.put("createBy", user.getUserId());
		if(taskQueryDTO.getCreateDate() != null)
			params.put("createDate", DateUtil.formatYearMonthDay(taskQueryDTO.getCreateDate()));
		else
			params.put("createDate", "");
		pagination.setParams(params, pageable);
		
		return SimpleResponse.success(taskService.findByPage(pagination), response);
	}
	
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "",  RoleEnum.CMCC_VALUE + "", RoleEnum.BRANCH_VALUE + ""})
	@GetMapping("/page/success/{taskId}")
	public SimpleResponse querySuccess(
			@PathVariable("taskId") int taskId,
			@Valid TaskDetailDTO taskDetailDTO,
			@PageableDefault(page=PageConstants.DEFAULT_PAGE_NO,size=PageConstants.DEFAULT_PAGE_SIZE)
			@SortDefault.SortDefaults({
				@SortDefault(sort = "imei_no", direction = Direction.ASC)
			}) Pageable pageable,
			HttpServletResponse response) throws Exception {
		log.info("taskId:" + taskId + ",pageable:" + pageable);
		
		Pagination<TaskDetail> pagination = new Pagination<TaskDetail>(pageable);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params = BeanMapUtils.beanToMap(taskDetailDTO);
		params.put("taskId", taskId);
		pagination.setParams(params, pageable);
		
		return SimpleResponse.success(taskService.findSuccessByPage(pagination), response);
	}
	
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "",  RoleEnum.CMCC_VALUE + "", RoleEnum.BRANCH_VALUE + ""})
	@GetMapping("/page/failure/{taskId}")
	public SimpleResponse queryFailure(
			@PathVariable("taskId") int taskId,
			@Valid TaskDetailDTO taskDetailDTO,
			@PageableDefault(page=PageConstants.DEFAULT_PAGE_NO,size=PageConstants.DEFAULT_PAGE_SIZE)
			@SortDefault.SortDefaults({
				@SortDefault(sort = "imei_no", direction = Direction.ASC)
			}) Pageable pageable,
			HttpServletResponse response
		) throws Exception {
		log.info("taskId:" + taskId + ",pageable:" + pageable);
		
		Pagination<TaskDetail> pagination = new Pagination<TaskDetail>(pageable);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params = BeanMapUtils.beanToMap(taskDetailDTO);
		params.put("taskId", taskId);
		pagination.setParams(params, pageable);
		
		return SimpleResponse.success(taskService.findFailureByPage(pagination), response);
	}
	
	@SuppressWarnings("unchecked")
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "",  RoleEnum.CMCC_VALUE + "", RoleEnum.BRANCH_VALUE + ""})
	@PostMapping("/file/{targetId}")
	public SimpleResponse create(
			@PathVariable("targetId") int targetId,
			@RequestParam("dataFile") MultipartFile dataFile,
			HttpServletResponse response) throws Exception {
		log.info("file:{size:" + dataFile.getSize() + ",name:" + dataFile.getOriginalFilename() + ",contentType:" + dataFile.getContentType());
		
		User user = tokenUtil.getUser();
		if(user.getUserId() == targetId) {
			return SimpleResponse.badRequest("不能调拨给自己", response);
		}
		
		if(!dataFile.getOriginalFilename().endsWith("xls") && !dataFile.getOriginalFilename().endsWith("xlsx"))
			return SimpleResponse.badRequest("文件格式不正确", response);
		
		ImportParams params = new ImportParams();
		List<TaskDetailExcelDTO> taskDetailExcelList = new ArrayList<TaskDetailExcelDTO>();
		try {
			taskDetailExcelList = (List<TaskDetailExcelDTO>) ExcelUtil.importExcel(dataFile.getInputStream(), TaskDetailExcelDTO.class, params);
			if(taskDetailExcelList.size() == 0)
				return SimpleResponse.failed("导入的是张空表", response);
		} catch(NoSuchElementException e) {
			return SimpleResponse.failed("导入的模板不正确", response);
		}
			
		List<TaskDetail> taskDetailList = new ArrayList<TaskDetail>();
		taskDetailExcelList.forEach(t->{
			TaskDetail taskDetail = new TaskDetail();
			taskDetail.setImeiNo(t.getImeiNo());
			taskDetailList.add(taskDetail);
		});
		
		Task task = new Task();
		task.setCreateBy(user.getUserId());
		task.setCreateDate(new Date());
		
		if(!taskService.addTask(task, taskDetailList, targetId)) {
			SimpleResponse.failed("调拨操作失败", response);
		}
		
		return SimpleResponse.success("调拨操作完成，详情请看任务报表", response);
	}
	
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "", RoleEnum.CMCC_VALUE + "", RoleEnum.BRANCH_VALUE + ""})
	@PostMapping("/{targetId}")
	public SimpleResponse create(
			@PathVariable("targetId") int targetId,
			@RequestBody @Valid List<TaskDetail> taskDetail,
			HttpServletResponse response) throws Exception {
		log.info("taskDetail.size=" + taskDetail.size());
		
		User user = tokenUtil.getUser();
		if(user.getUserId() == targetId) {
			return SimpleResponse.badRequest("不能调拨给自己", response);
		}
		
		Task task = new Task();
		task.setCreateBy(user.getUserId());
		task.setCreateDate(new Date());
		
		if(!taskService.addTask(task, taskDetail, targetId)) {
			SimpleResponse.failed("调拨操作失败", response);
		}
		
		return SimpleResponse.success("调拨操作完成，详情请看任务报表", response);
	}
	
}
